<template>
  <div>
    <el-form class="projectForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
      <el-tabs v-model="activeTabIndex" @tab-click="TabClick" style="width:100%;margin-left: 8px">
        <el-tab-pane label="基本内容" name="0" >
          <el-form-item label="项目名称" prop="fName">
            <el-input v-model="formData.fName" placeholder="请输入项目名称" clearable :style="{width: '100%'}"
                      :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="fNumber">
            <el-input v-model="formData.fNumber" placeholder="请输入项目编号" clearable :style="{width: '100%'}"
                      :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="产业类型" prop="fType" v-if="false">
            <el-input v-model="formData.fType" placeholder="请输入产业类型（种植品种）" clearable :style="{width: '100%'}"
                      :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="建设地点" prop="fAddress" >
            <el-input v-model="formData.fXzqmc" class="xjxzq-input" :readonly="true"></el-input>
            <el-input v-model="formData.fAddress" placeholder="请输入详细建设地点()" clearable
                      style="width: 100%;margin-top: 10px;" :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="建设内容" prop="fContent">
            <el-input class="addressDetail" v-model="formData.fContent" type="textarea" placeholder="请输入建设内容"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}" :readonly="showAdd.readonly"
            ></el-input>
          </el-form-item>
          <el-form-item label="建设规模（万亩）" prop="fScaleArea" v-if="false">
            <el-input v-model="formData.fScaleArea" placeholder="请输入建设规模（万亩）" clearable :style="{width: '100%'}"
                      oninput="value=value.replace(/[^0-9.]/g,'')" :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item size="large">
            <el-col>
              <el-button type="primary" circle @click="MovetoPage(1)" icon="el-icon-right"></el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="矢量范围" name="1">
          <el-row type="flex" justify="start" align="top" v-if="false">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="fIrrigatePen">
                <el-input v-model="formData.fIrrigatePen" placeholder="项目名称" clearable :style="{width: '100%'}"
                          :readonly="showAdd.readonly"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="项目范围">
              <el-button type="primary" @click="openLoadshpPanel" style="float: left">上传shp</el-button>
              <Loadshp :map="map" :mcShow="mcShow" v-if="mcShow.uploadshp==='loadshp'"
                       :handleLoadFeatoMap="handleLoadFeatoMap"
              ></Loadshp>
            </el-form-item>
          </el-row>
          <el-form-item size="large">
            <el-col :span="12">
              <el-button type="primary" circle @click="MovetoPage(-1)" icon="el-icon-back"></el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" circle @click="MovetoPage(1)" icon="el-icon-right"></el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane v-for="(item,panename) in divType" :label="item.cn" :name="item.panename">
          <div>
            <el-form-item size="large">
              <el-row>
                <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
                <el-button type="primary" :value="item.name" @click="StartAnalysis" size="medium"
                           :disabled="analyDisabled"
                >开始分析
                </el-button>
              </el-row>
              <el-row class="cbstform">
                <div class="emptyinfo" v-if="item.attributeShow===false">
                  分析结果为空<br/>当前项目不与{{ item.cn }}重叠
                </div>
                <AttributeTable v-if="item.attributeShow===true" :tableconfig="item.attributeTable2"
                                :overSource="overSource"
                ></AttributeTable>
                <AnalysisStatistic :attributeTable="item.attributeTable" :divType="item.name"
                                   :overSource="overSource"  v-if="item.attributeShow===true"
                ></AnalysisStatistic>
              </el-row>
              <el-row v-if="formData.fId != null" class="cbstform">
                <div class="seeinfo">提供的分析结果如下所示</div>
                <div class="seeinfo" v-if="item.anaATFeasConfig.length===0">
                  分析结果为空，表明该项目与{{ item8.cn }}不相交
                </div>
                <AttributeTable v-if="item.anaATFeasConfig.length===5" :overSource="overSource"
                                :tableconfig="item.anaATFeasConfig"
                ></AttributeTable>
                <CbProStatisticTable v-if="item.anaATFeasConfig.length===5"
                                     :staticsTable="JSON.parse(formData_Ori.fHistorygbzTable)"
                                     :infoflag="item.cn"
                ></CbProStatisticTable>
              </el-row>

            </el-form-item >
            <el-form-item size="large" class="next-last" v-if="item.lastFlag!=true">
              <el-row>
                <el-col :span="12">
                  <el-button type="primary" circle @click="MovetoPage(-1)" icon="el-icon-back"></el-button>
                </el-col>
                <el-col :span="12">
                  <el-button type="primary" circle @click="MovetoPage(1)" icon="el-icon-right"></el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item size="large" class="next-last" v-if="item.lastFlag===true">
              <el-row>
                <el-col :span="12">
                  <el-button type="primary" circle @click="MovetoPage(-1)" icon="el-icon-back"></el-button>
                </el-col>
                <el-col :span="12">
                  <!--              <el-button type="primary" circle @click="Next(7)" icon="el-icon-right"></el-button>-->
                  <el-button type="danger" class="savebtn" @click="submitForm" v-if="showAdd.readonly===false">导出结果
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-tab-pane>


      </el-tabs>
    </el-form>
    <div>
      <MapComp ref="mapComp" class="right-panel"></MapComp>
      <ViewVerify v-show="formData.todotype === 'todo'"
                  :row="formData"
                  :taskDefKey="formData.taskDefKey?formData.taskDefKey.toString():'0'"
                  :taskId="formData.taskId?formData.taskId.toString():'0'"
                  :taskName="formData.taskName?formData.taskName.toString():'0'"
                  :type="formData.todotype"
                  :showAdd="showAdd"
                  class="ri-bot"
      >
      </ViewVerify>
    </div>
    <!--    <div ref="closeCP" class="closeCP" @click="closeThisCom">关闭</div>-->
    <el-button
      type="danger"
      size="mini"
      class="closeCP"
      @click="closeThisCom"
    >关闭
    </el-button>

  </div>
</template>
<script>
import MapSource from '@/components/Map/MapSource'
import DrawPlotting from '@/components/Map/DrawPlotting'
import globalmf from '@/utils/Global/GlobalMapFunction'
import Catalog from '@/views/business/gbzcb/Catalog'
import AnalysisStatistic from '@/views/business/gbzcb/AnalysisStatistic'
import AttributeTable from '@/views/business/gbzcb/AttributeTable'
// import gConfig from '@/utils/GlobalConfig'
import axios from 'axios'
import Bus from '@/utils/bus'
import { addGbzcb, updateGbzcb } from '@/api/business/gbzcb'
import { getxzqGeom } from '@/api/gbznt/gbzCommon'
import request from '@/utils/request'
import XzqList from '@/components/Xzq/XzqList'
import CbProStatisticTable from '@/views/business/gbzcb/CbProStatisticTable'
import ViewVerify from '@/components/Activiti/ViewVerify/ViewVerify'
import printtest from '@/views/business/gbzcb/printtest'
import { Loading } from 'element-ui'
import { getCatalogQueryConfigListByIds, getXzqServerConfigList } from '@/api/portal/catalog'
import { uploadShpFileZip } from '@/api/portal/ioGisFile'
import Loadshp from '@/components/Map/Loadshp'
import MapComp from '@/components/Map/mapComp'

export default {
  components: {
    Loadshp,
    CbProStatisticTable,
    XzqList,
    MapSource,
    DrawPlotting,
    Catalog,
    AnalysisStatistic,
    ViewVerify,
    printtest,
    AttributeTable,
    MapComp
  },
  props: {
    showAdd: {
      type: Object,
      default() {
        return {}
      }
    },
    taskId: {
      type: String
    },
    taskName: {
      type: String
    },
    type: {
      type: String,
      default: 'none'
    },
    formData: {
      type: Object,
      default() {
        return {}
      }
    }

  },
  data() {
    return {
      printObj: {
        id: 'proPrintTest',//id
        popTitle: '我是标题'//自定义设置标题
      },
      loadingtext: '',
      mapSourceLoad: false,//mapSource加载
      layerVisable: false,//高标准农田的所有专题数据不能显示，因为运行在外网。
      divType: {
        historyproject: {
          panename:"2",
          name: 'historyproject',
          ftable: 'fHistorygbzTable',
          ffeas: 'fHistorygbzFeas',
          cn: '土地规划',
          analysisFeatures:null,
          anaATFeasConfig:[],
          analysisTable:null,
          attributeShow:null,
          attributeTable2:null
        },
        naturalreserve: {
          panename:"3",
          name: 'naturalreserve',
          ftable: 'fNaturalreserveTable',
          ffeas: 'fNaturalreserveFeas',
          cn: '城市规划',
          analysisFeatures:null,
          anaATFeasConfig:[],
          analysisTable:null,
          attributeShow:null,
          attributeTable2:null
        },
        redline: {
          panename:"4",
          name: 'redline',
          ftable: 'fRedlineTable',
          ffeas: 'fRedlineFeas',
          cn: '生态红线' ,
          analysisFeatures:null,//相交features
          anaATFeasConfig:[],//已经相交过的结果存储表
          analysisTable:null,//相交feature对应的属性表
          attributeShow:null,//相交feature对应的统计表,
          attributeTable2:null
        },

        waterprotect: {
          panename:"5",
          name: 'waterprotect',
          ftable: 'fWaterprotecTable',
          ffeas: 'fWaterprotectFeas',
          cn: '基本农田' ,
          analysisFeatures:null,
          anaATFeasConfig:[],
          analysisTable:null,
          attributeShow:null,
          attributeTable2:null
        },
        farmland2018: {
          panename:"6", name: 'farmland2018',
          ftable: 'fFarmland2018Table',
          ffeas: 'fFarmland2018Feas',
          cn: '安全局范围' ,
          analysisFeatures:null,
          anaATFeasConfig:[],
          analysisTable:null,
          attributeShow:null,
          attributeTable2:null,
          lastFlag:true,
        }
        // landspace:  {name:'landspace',ftable:'fLandspaceTable',ffeas:'fLandspaceFeas',cn:"国土空间规划"}
  },
      formData_Ori: {},
      fileList: [],
      map: null,
      viewNow: null,
      overSource: null,
      overSourceXJ: null,
      overVector: null,
      prj: null,
      prjCode: '4490',
      prjCodeStr: 'EPSG:4490',
      sketch: null,
      measure: null,
      snap: null, //捕捉
      measureTooltipElement: null,
      measureTooltip: null,
      analysisLayerType: '',
      queryLayer: null,//当前要分析的图层
      analysisLayers: [],
      analysisDraw: null,
      drawFeatures: [],
      attributeTable: {},//用于统计
      attributeTable2: null,//用于分析属性表
      config: {
        regionDatasourceName: null,
        regionDatasetName: null,
        regionFieldName: null,
        featurePicName: '',
        mapCenter: { x: 126, y: 46 },
        'projectLayerTreeData': [
          {
            name: 'historyproject',
            label: '土地规划',
            id: 'b68abc9c-46f1-489e-9563-25712aa90ace',
            type: 1
          },
          {
            name: 'redline',
            label: '生态红线',
            id: '0e57aea6-e05c-41f0-a658-389c10067967',
            type: 1
          },
          {
            name: 'naturalreserve',
            label: '城市规划',
            id: '9681e3b5-9044-460a-9fe0-af4870151627',
            type: 1
          },
          {
            name: 'waterprotect',
            label: '基本农田',
            id: '08f71d08-090e-4acf-b83b-f28bafa5faca',
            type: 1
          },
          {
            name: 'farmland2018',
            label: '安保局核查',
            id: '9d7e020b-d6e5-4894-9b6b-146381ac48de',
            type: 1
          }
          // {
          //   name: 'landspace',
          //   label: '国土空间规划',
          //   id: '64990b7f-1ec2-4f90-8da2-e8ec4114c4e5',
          //   type: 1
          // }
        ]
      },
      x2js: null,
      activeName: 'first',
      activeTabIndex: '0',
      project: {
        feature: null
      },
      rules: {
        fName: [{
          required: true,
          message: '请输入项目名称',
          trigger: 'blur'
        }],
        fNumber: [{
          required: false,
          message: '请输入项目编号',
          trigger: 'blur'
        }],


        fIrrigatePen: [],
        fIrrigateWei: [],
        fIrrigateGuan: [],
        fPlanCentral: [],
        fPlanShixian: [],
        fPlanSelf: []
      },
      showBtn: {
        measureLength: true,
        measureArea: true,
        drawPlotting: true,
        localPosition: true,
        rightbtns: 'allClose',
        clearSelected: true
      },
      mcShow: {
        uploadshp: 'close',
        loPosition: true,
        drawPlotting: 'allClose',//标绘
      },
      inshpStyle: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(250,250,250,0.0)'
        }),
        stroke: new ol.style.Stroke({
          color: '#00ffff', //'#d74a4a',
          width: 2
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#00ffff'
          })
        })
      })

    }
  },
  computed: {
    analyDisabled() {
      if (this.showAdd.tododeal === true) {
        return false//办理的时候可以分析，因此disabled是false
      } else if (this.showAdd.readonly === true) {
        return true
      } else {
        return false
      }
    },
    setVisible: function() {
      return function(arg1) {
        let result = false
        for (let i = 0; i < arg1.length; i++) {
          if (arg1[i] === true) {
            result = true
          }
        }
        return result
      }
    }

  },
  watch: {},
  created() {
    if (this.formData.fId != null) {//不是新增项目。不允许修改所选择的行政区。
      this.formData_Ori = _.cloneDeep(this.formData)//深度拷贝
    }
    //分析统计后的结果，返回给formData
    Bus.$on('createGBZCBProjectSaveStatisticTable', msg => {
      let that = this
      switch (msg.type) {
        case 'historyproject':
          that.formData.fHistorygbzTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'redline':
          that.formData.fRedlineTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'waterprotect':
          that.formData.fWaterprotecTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'landspace':
          //that.formData.fLandspaceTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'naturalreserve':
          that.formData.fNaturalreserveTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
      }
    })
    Bus.$on('createGBZCBProjectreReapplySubmit', msg => {
      let that = this
      that.submitForm()
    })
  },
  mounted() {
    //获取当前用户的geom
    this.$nextTick(() => {
     this.map = this.$refs.mapComp.map
     this.overSource = this.$refs.mapComp.overSource
     this.InitMapSource()
    })

    if (this.formData.fId != null) {//新增项目
      this.$nextTick(() => {
        this.initNotCreate()
        this.initNotCreateFeas('fHistorygbzFeas', 'historyproject')
        this.initNotCreateFeas('fRedlineFeas', 'redline')
        this.initNotCreateFeas('fWaterprotectFeas', 'waterprotect')
        this.initNotCreateFeas('fNaturalreserveFeas', 'naturalreserve')
      })
    }
  },
  methods: {
    openLoadshpPanel() {
      this.mcShow.uploadshp = 'loadshp'
    },
    //修改或者浏览时的初始化代码。
    initNotCreate() {
      //2.读取项目geometry。
      let format = new ol.format.WKT()
      let featureGbz = format.readFeature(this.formData.geom, {//默认就是4490的坐标
        dataProjection: 'EPSG:4490',
        featureProjection: this.map.getView().getProjection().getCode()
      })
      // feature.getGeometry().getType()可能为GeometryCollection,
      let feas = []
      let geomType = featureGbz.getGeometry().getType().toLowerCase()
      if (geomType === 'geometrycollection') {//好几个面的话就是
        let geos = featureGbz.getGeometry().getGeometries()
        for (let i = 0; i < geos.length; i++) {
          let fea = new ol.Feature({ geometry: geos[i] })
          feas.push(fea)
        }
      } else {
        let geo = featureGbz.getGeometry()
        let fea = new ol.Feature({ geometry: geo })
        feas.push(fea)
      }
      this.project.feature = feas
      this.ZoomToExtent()

    },
    // region 分析事件
    InitAnalysis() {
      let that = this
      axios.all([that.QueryServiceQueryDataAjax(), that.XzqServiceQueryDataAjax()])
        .then(axios.spread(function(queryCatalog, QueryXZQ) {	// spread是将各请求结果拆分返回，如果不使用改方法，则最后的相应结果为一个数组[resp1, resp2]
            //第一个请求
            if (queryCatalog.data.queryData.length > 0) {
              for (var i in queryCatalog.data.queryData) {
                var obj = queryCatalog.data.queryData[i]
                var name = obj.f_name
                var id = obj.f_catalogid
                var dataUrl = obj.f_url //数据服务地址
                var analysisUrl = obj.f_analysisurl //分析服务地址
                var datasourceNames = [{ 'name': obj.f_datasource, 'value': obj.f_datasource }]
                var datasetNames = [{ 'name': obj.f_dataset, 'value': obj.f_dataset }]
                var fieldData = JSON.parse(obj.f_fieldconfig)
                if (analysisUrl != null && analysisUrl != '') {
                  var layerjson = {
                    'name': name,
                    'id': id,
                    'dataUrl': dataUrl,
                    'analysisUrl': analysisUrl,
                    'datasourceName': datasourceNames[0].name,
                    'datasetName': datasetNames[0].name,
                    'fieldData': fieldData
                  }
                  that.analysisLayers.push(layerjson)
                }
              }
            }
            //第二个请求
            if (QueryXZQ.data.queryData.length > 0) {
              var obj = QueryXZQ.data.queryData[0]
              that.dataUrl = obj.f_url
              that.config.regionDatasourceName = obj.datasource
              that.config.regionDatasetName = obj.dataset
              that.config.regionFieldName = obj.field
            }
            that.AnalysisProcess()
          }
          )
        )
    },
    QueryServiceQueryDataAjax() {
      var that = this
      that.analysisLayers = []
      var serviceids = []
      for (let i = 0; i < that.config.projectLayerTreeData.length; i++) {
        serviceids.push(that.config.projectLayerTreeData[i].id)
      }
      // that.map.getLayers().forEach(function(layer, i) {
      //   if (layer.get('id')) {
      //     serviceids.push(layer.get('id'))
      //   }
      // })
      let seridsStrTemp = JSON.stringify(serviceids)
      let seridsStr = seridsStrTemp.replace('[', '')
      seridsStr = seridsStr.replace(']', '')
      seridsStr = seridsStr.replace('"', '')
      return getCatalogQueryConfigListByIds({
        'serviceIds': seridsStr.trim()
      })
    },
    XzqServiceQueryDataAjax() {
      return getXzqServerConfigList()
    },

    StartAnalysis(e) {
      let that = this
      if (this.formData.fXzqdm === null || this.formData.fXzqdm.endsWith('00')) {
        that.$message({
          message: '请先选择项目建设地点（所在区县）',
          type: 'error'
        })
        return
      }

      that.analysisLayerType = e.currentTarget.getAttribute('value')
      that.queryLayer = that.config.projectLayerTreeData.find((item, index) => {
        return item.name == that.analysisLayerType
      })
      if (that.queryLayer) {
        //初始化分析参数
        that.InitAnalysis()
      }
    },
    AnalysisProcess() {
      let that = this
      that.drawFeatures = that.overSource.getFeatures()
      that.loadingtext = '正在检查导入shapefile范围正确性'
      const loading = this.$loading({
        lock: true,
        customClass: 'create-isLoading',  // *这里设置他的class名称,这里最重要
        text: that.loadingtext,
        spinner: 'el-icon-loading',
        background: 'rgba(83,80,80,0.7)'
      })
      loading.$el.style.fontSize = '50px'
      var analysisGeometries = []
      try {
        for (var i in that.drawFeatures) {
          //why20211018转换投影
          var defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
          var mapPrjCode = that.map.getView().getProjection().getCode()
          if (defaultPrjCode != mapPrjCode) {
            that.drawFeatures[i].getGeometry().transform(that.map.getView().getProjection().getCode(),
              that.globalVar.mmConfig.mapRegion.prjcode)
          }
          analysisGeometries.push(that.drawFeatures[i].getGeometry())
        }

        for (var i in that.analysisLayers) {
          var layer = that.analysisLayers[i]
          var name = layer['name']
          var id = layer['id']
          if (that.queryLayer && that.queryLayer.id == id) {
            var dataUrl = layer['dataUrl'] //数据服务地址
            var analysisUrl = layer['analysisUrl'] //分析服务地址
            var datasourceName = layer['datasourceName']
            var datasetName = layer['datasetName']
            var fieldData = layer['fieldData']
            //解析分析字段
            var analyseFields = []
            that.config.analysisFields = []
            for (var i in fieldData) {
              var field = fieldData[i]
              var fieldEn = field['f_field']
              var fieldCn = field['f_fieldcn']
              var isvisible = field['f_isvisible']
              var unit = field['f_unit']
              if (isvisible == 1) {
                that.config.analysisFields.push(field)
                analyseFields.push(fieldEn)
              }
            }
            //手绘图形与县界范围做相交
            var sourcedatasetname = that.config.regionDatasetName + '@' + that.config.regionDatasourceName //"XDV700NCFW@smkjk";
            var datasetOverlayAnalystParameters = new SuperMap.DatasetOverlayAnalystParameters({
              sourceDataset: sourcedatasetname,
              operateRegions: analysisGeometries, //[drawFeature.getGeometry()],
              sourceDatasetFields: [that.config.regionFieldName],
              tolerance: 0,
              operation: SuperMap.OverlayOperationType.INTERSECT,
              resultSetting: new SuperMap.DataReturnOption({
                expectCount: 0//不加上这一句，就只返回最多1000条结果
              })
            })
            new ol.supermap.SpatialAnalystService(analysisUrl).overlayAnalysis(datasetOverlayAnalystParameters, function(serviceResult) {
              globalmf.clearSelectedFeature(that.map, that.overSource)
              if (!serviceResult.result) {
                loading.close()
                that.$message({
                  message: '输入的图形与行政区界线相交为空！无法进行下一步分析',
                  type: 'error'
                })
                return
              }
              var result = serviceResult.result.recordset.features
              var features = (new ol.format.GeoJSON()).readFeatures(result)
              that.overSource.clear()

              //判断当前相交图形是否属于本账号所在范围
              var geometries = []
              for (var i = 0, l = features.length; i < l; i++) {
                var feature = features[i]
                var attributes = feature.getProperties()
                var code = attributes[that.config.regionFieldName]
                //   var userCode = that.globalVar.mmConfig.mapRegion['f_regioncode']
                //var userLevel = that.globalVar.mmConfig.mapRegion['f_levels']
                //  if (code == userCode || code.substr(0, 3) == userCode || userLevel == 1) {
                if (code === that.formData.fXzqdm) {//只能分析指定的区县。
                  geometries.push(features[i].getGeometry())
                }
              }
              if (geometries.length > 0) {
                //数据图层与范围图层叠加分析
                var sourcedatasetname = datasetName + '@' + datasourceName
                var datasetOverlayAnalystParameters = new SuperMap.DatasetOverlayAnalystParameters({
                  sourceDataset: sourcedatasetname,
                  operateRegions: geometries,
                  tolerance: 0,
                  sourceDatasetFields: analyseFields,
                  operation: SuperMap.OverlayOperationType.INTERSECT,
                  resultSetting: new SuperMap.DataReturnOption({
                    expectCount: 0//不加上这一句，就只返回最多1000条结果
                  })
                })
                that.loadingtext = '正在与专题数据进行叠被分析'
                // alert("正在与专题数据进行叠被分析");
                loading.setText(that.loadingtext)
                new ol.supermap.SpatialAnalystService(analysisUrl).overlayAnalysis(datasetOverlayAnalystParameters, function(serviceResult) {
                  globalmf.clearSelectedFeature(that.map, that.overSource)
                  if (!serviceResult.result) {
                    that.divType[that.analysisLayerType].attributeShow=false
                   // let ftableName = that.divType[that.analysisLayerType].ftable;
                    that.formData[that.divType[that.analysisLayerType].ftable] = '{"stainfo":"empty"}'
                    that.formData[that.divType[that.analysisLayerType].ffeas] = '{"stainfo":"empty"}'
                    loading.close()
                    return
                  }
                  var result = serviceResult.result.recordset.features
                  var features = (new ol.format.GeoJSON()).readFeatures(result)
                  if (features.length > 0) {
                    that.overSource.clear()
                    //why20211018转换投影
                    var defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
                    var mapPrjCode = that.map.getView().getProjection().getCode()
                    if (defaultPrjCode != mapPrjCode) {
                      that.features[0].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
                      for (var i = 0; i < features.length; i++) {
                        features[i].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
                      }
                    }
                    for (var i = 0; i < features.length; i++) {
                      features[i].setStyle(() => {
                        return new ol.style.Style({
                          fill: new ol.style.Fill({
                            color: 'rgba(100,100,100,0)'
                          }),
                          stroke: new ol.style.Stroke({
                            color: '#62ff00', //'#d74a4a',#ffcc33
                            width: 2
                          })
                        })
                      })
                    }
                    that.overSource.addFeatures(features)
                    that.divType[that.analysisLayerType].attributeTable = {
                      features: features,
                      serviceId: that.queryLayer.id,
                      divType: that.analysisLayerType
                    }
                    let aftObj = { feaResult: result, anaFields: that.config.analysisFields }
                    that.divType[that.analysisLayerType].attributeTable2 = [features, that.config.analysisFields, that.map, '', '']
                    that.divType[that.analysisLayerType].analysisFeatures= JSON.stringify(aftObj)
                    that.divType[that.analysisLayerType].attributeShow=true

                    loading.close()
                  } else {
                    that.divType[that.analysisLayerType].attributeShow=false
                 //   that.mcShow.showEmptyResult[that.analysisLayerType] = true
                    that.formData[that.divType[that.analysisLayerType].ftable] = '{"stainfo":"empty"}'
                    that.formData[that.divType[that.analysisLayerType].ffeas] = '{"stainfo":"empty"}'
                    loading.close()
                  }

                })

              } else {
                that.$message.error('输入的图形范围超过对应的行政区界线')
                loading.close()
              }
            })

          }

        }
      } catch (err) {
        loading.close()
        that.$message.error('分析出错', err)

      }
    },

    InitMapSource() {
      let that = this
      that.overSourceXJ = new ol.source.Vector({ crossOrigin: 'anonymous', wrapX: false })
      that.overVector = new ol.layer.Vector({
        source: that.overSourceXJ
      })
      that.map.addLayer(that.overVector)
      that.overVector.setZIndex(9999)
      if (that.globalVar.mmConfig.mapRegion.geomwkt) {
        let format = new ol.format.WKT()
        let featureXJ = format.readFeature(that.globalVar.mmConfig.mapRegion.geomwkt, {//默认就是4490的坐标
          dataProjection: 'EPSG:4490',
          featureProjection: this.map.getView().getProjection().getCode()
        })
        featureXJ.setStyle(() => {
          return new ol.style.Style({
            fill: new ol.style.Fill({
              color: 'rgba(100,100,100,0)'
            }),
            stroke: new ol.style.Stroke({
              color: '#fe2525', //'#d74a4a',#ffcc33
              width: 3
            })
          })
        })
        that.overSourceXJ.addFeature(featureXJ)
        let viewold = that.map.getView()
        that.ZoomToOverSource(that.overSourceXJ)
      }
    },
    //endregion
    // region 地图事件
    ZoomToExtent() {
      let that = this
      that.overSource.clear()
      if (that.project.feature) {
        that.overSource.addFeatures(that.project.feature)
        that.ZoomToOverSource(that.overSource)
      } else {
        that.$message({
          message: '请在详细信息中上传项目范围',
          type: 'warning'
        })
      }

    },

    TabClick(tab) {
      let that = this
      // console.log(tab)
      that.activeTabIndex = tab.index//记录下现在的index
      that.Next(that.activeTabIndex)
    },
    MovetoPage(num) {
      let nowIndex = parseInt(this.activeTabIndex)
      nowIndex = nowIndex + num
      this.activeTabIndex = nowIndex.toString()
      this.Next(this.activeTabIndex)
    },
    Next(index) {
      index = parseInt(index)
      let that = this
      switch (index) {
        case 0:
          //    that.activeName = 'first'
          break
        case 1:
          //  that.activeName = 'second'
          break
        case 2:
          that.ZoomToExtent()
          //  that.activeName = 'third'
          if (that.project.feature) {
            //   that.openData('historyproject')
          }
          break
        case 3:
          //打开生态红线数据
          that.ZoomToExtent()
          // that.activeName = 'fourth'
          if (that.project.feature) {
            // that.openData('redline')
          }
          break
        case 4://自然保护区
          that.ZoomToExtent()
          //  that.activeName = 'fifth'
          if (that.project.feature) {
            //  that.openData('naturalreserve')
          }
          break
        case 5://水源地保护
          that.ZoomToExtent()
          // that.activeName = 'sixth'
          if (that.project.feature) {
            //  that.openData('waterprotect')
          }
          break
        case 6://国土空间规划
          that.ZoomToExtent()
          // that.openData('landspace')
          // that.activeName = 'seventh'
          break
      }
    },

    feaReProject(features) {
      let that = this
      if (features.length > 0) {
        //why20211018转换投影
        let defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
        let mapPrjCode = that.map.getView().getProjection().getCode()
        if (defaultPrjCode != mapPrjCode) {
          that.fresult[0].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
          for (let i = 0; i < features.length; i++) {
            features[i].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
          }
        }
      }
      return features
    },

    initNotCreateFeas(feas, atfc) {
      if (!this.formData_Ori[feas]) {
        this.divType[atfc].anaATFeasConfig=[]
        return
      }
      let fs = JSON.parse(this.formData_Ori[feas])
      if (fs.hasOwnProperty('stainfo')) {//表示空
        this.divType[atfc].anaATFeasConfig=[]
      } else if (fs.hasOwnProperty('feaResult')) {
        let fresult = fs.feaResult
        let features = (new ol.format.GeoJSON()).readFeatures(fresult)
        features = this.feaReProject(features)
        let tc = [features, fs.anaFields, this.map, '', '']
        this.divType[atfc].anaATFeasConfig= tc
      } else {
        this.divType[atfc].anaATFeasConfig=[]
      }
    },

    //endregion
    submitForm() {
      let that = this
      //1.填写项目状态
      that.formData.fState = 0//建设状态 0代表存在 2代表删除,1表示通过审批，正式成为储备项目
      //2.填写formData上传shp的几何信息和分析矢量图形,在上传shp时已经赋值了geom
      that.formData.fHistorygbzFeas = (that.divType["historyproject"].analysisFeatures==null) ? that.formData.fHistorygbzFeas : that.divType["historyproject"].analysisFeatures
      that.formData.fRedlineFeas = (that.divType["redline"].analysisFeatures==null) ? that.formData.fRedlineFeas : that.divType["redline"].analysisFeatures
      that.formData.fWaterprotectFeas = (that.divType["waterprotect"].analysisFeatures==null) ? that.formData.fWaterprotectFeas : that.divType["waterprotect"].analysisFeatures
      that.formData.fNaturalreserveFeas = (that.divType["naturalreserve"].analysisFeatures==null) ? that.formData.fNaturalreserveFeas : that.divType["naturalreserve"].analysisFeatures
      if (this.formData.fXzqdm === null) {
        that.$message({
          message: '必须填写项目所在区县!',
          type: 'error'
        })
        return
      }
      //4.各类项目分析后的统计表查看，有null的表示没有分析，不允许。直接return，
      for (let i in this.formData) {
        if (i.endsWith('Table')) {
          if (this.formData[i] === null) {
            that.$message({
              message: '有叠被数据没有被分析，请先进行分析!',
              type: 'error'
            })
            return
          }
        }
      }
      //5.验证表单必填项是否填写
      that.$refs['elForm'].validate(valid => {
        // TODO 提交表单
        if (valid) {
          if (that.formData.fId === null) {//没有id表示是新增的
            addGbzcb(that.formData).then(response => {
              that.msgSuccess('新增成功')
              that.open = false
              that.showAdd.showcp = false
              // that.getList()
            })
          } else {//有id表示表示有项目，是修改或者查看
            that.formData.updateTime = null
            that.formData.createTime = null
            updateGbzcb(that.formData).then(response => {
              that.msgSuccess('修改成功')
              that.open = false
              that.showAdd.showcp = false
              // that.getList()
            })
          }

        } else {
          that.$message({
            message: '有必填项没有被填写，请检查!',
            type: 'error'
          })
        }
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    closeThisCom() {
      let that = this
      if (that.showAdd.readonly === true) {
        that.showAdd.showcp = false
      } else {
        this.$confirm('是否关闭项目储备页面？ 关闭后所有已填写的信息都不会保留！', '警告', {
          confirmButtonText: '确定关闭',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          that.showAdd.showcp = false
          that.showAdd.showcp = false
        })
      }
    },
    //上传shp的回调函数
    handleLoadFeatoMap(feas) {
      this.overSource.addFeatures(feas)
      this.project.feature = feas
      let format = new ol.format.WKT()
      this.formData.geom = format.writeFeatures(this.project.feature)
      //  this.ZoomToOverSource(this.overSource)
    },
    ZoomToOverSource(cuOverSource) {
      var that = this
      if (cuOverSource == null) {
        return
      }
      if (cuOverSource.getFeatures().length == 0) {
        return
      }
      var extent = cuOverSource.getExtent()
      //  var extent2 = cuOverSource.getExtent()
      let extent2 = [extent[0] - 0.2, extent[1] - 0.2, extent[2] + 0.2, extent[3] + 0.2]
      var extentObj = {
        center: { x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2 },
        width: Math.abs(extent[2] - extent[0]),
        height: Math.abs(extent[3] - extent[1])
      }
      // var tol = that.tol
      // if (extentObj.width < tol && extentObj.height < tol) {
      //   extent = [extentObj.center.x - tol / 2, extentObj.center.y - tol / 2, extentObj.center.x + tol / 2, extentObj.center.y + tol / 2]
      // }
      let viewold = that.map.getView()
      viewold.fit(extent2, { size: that.map.getSize(), padding: [20, 20, 20, 20] })
      setTimeout(function() {
        let viewnew = new ol.View({
          projection: ol.proj.get('EPSG:4490'), //ol.proj.get("EPSG:4326"),
          resolutions: viewold.getResolutions(),
          center: [extentObj.center.x, extentObj.center.y],
          // maxZoom: 18,
          // minZoom: 8,
          extent: extent2
          // Zoom: 8
          // constrainResolution: true,
          // smoothResolutionConstraint: true,
        })

        that.map.setView(viewnew)
        //  extent = cuOverSource.getExtent()
        //globalmf.zoomToExtent(that.map, extent)
        that.map.getView().setZoom(8)
        //   that.map.getView().setZoom(9);
        //  viewnew.fit(extent, { size: that.map.getSize(), padding: [20, 20, 20, 20] })
      }, 500)

      //
      // view.setMaxZoom(18);
      // view.setMinZoom(10);

    }
  },
  beforeDestroy() {
    Bus.$off('createGBZCBProjectSaveStatisticTable')
    Bus.$off('createGBZCBProjectreReapplySubmit')

  }

}
</script>
<style scoped>
/*令el-tabs可以有overflow*/
::v-deep .el-tabs--card {
  height: calc(100vh - 80px);
  /* overflow-y: auto; */
}

::v-deep .el-tab-pane {
  height: calc(100vh - 80px);
  overflow-y: auto;
}

.xjxzq-input {
  float: left;
  width: auto;
}

.ri-bot {
  position: absolute;
  right: 0;
  width: 40%;
  height: 150px;
  bottom: 0px;
  background-color: #eafdeb;
}

.next-last {
  margin: 10px 0px 70px 0px;
}

/*::v-deep .el-loading-spinner .el-loading-text{*/
/*  color: #19d1d4;*/
/*  font-size: 50px;*/
/*}*/


/*::v-deep .el-loading-spinner i {*/
/*  color: #19d1d4;*/
/*  font-size: 50px;*/
/*}*/
/*::v-deep .el-upload-dragger {*/
/*  width: 300px;*/
/*  height: 140px;*/
/*}*/

::v-deep .el-upload-dragger .el-icon-upload {
  font-size: 50px;
  line-height: 10px;
}


.el-form-item {
  text-align: center;
}

.el-form-item__content {
  margin-left: 0px !important;
}

.addressDetail {
  margin-top: 10px;
}

.mouse-position {
  position: absolute;
  bottom: 45px;
}

.projectForm {
  position: absolute;
  /*top: 15px;*/
  left: 0;
  width: 58%;
  height: 100%;
  /*overflow-y: auto;*/
}

/*#proMap {*/
/*  position: absolute;*/
/*  !*top: 15px;*!*/
/*  right: 0;*/
/*  width: 40%;*/
/*  height: 100%;*/
/*}*/
.right-panel {
  position: absolute;
  /*top: 15px;*/
  right: 0;
  width: 40%;
  height: 100%;
}

/*地图操作*/
.layer-switch {
  right: 8px;
  bottom: 40px;
  display: block;
  background-color: rgba(255, 255, 255, .5) !important;
  padding: 3px 3px 0px 3px;
  height: 30px;
  /* margin-bottom: 13px; */
  font-size: 16px;
  position: absolute;
  z-index: 1;
  border-radius: 4px;
  box-shadow: #000 0px 0px 5px;
}

.ol-scale-line {
  bottom: 25px !important;
}

.map-btns {
  position: absolute;
  z-index: 1;
  right: 8px;
  bottom: 170px;
  display: block;
  padding: 3px 3px 0px 3px;
  background-color: rgba(255, 255, 255, .5);
  border-radius: 4px;
}

.closeCP {
  position: absolute;
  z-index: 1;
  right: 8px;
  /*top: 10px;*/
  display: block;
  /*padding: 3px 3px 0px 3px;*/
  /*color: rgba(255, 249, 249);*/
  /*border-radius: 4px;*/
  /*background-color: #2fcba8;*/
  /*border-color: #ccc;*/
  /*height: 30px;*/
  /*width: 40px;*/
}

.map-btn {
  height: 30px;
  margin-bottom: 13px;
  font-size: 16px;
  line-height: 1.5;
}

.map-btns i {
  color: #ffffffeb;
  cursor: pointer;
  width: 25px;
  height: 25px;
  border-radius: 4px;
  display: inline;
  padding: 4px;
  background-color: #008680;
  border-color: #ccc;
}

.map-btn .sub-menu {
  right: 31px;
  display: flex;
  background-color: rgba(255, 255, 255, .5);
  position: absolute;
  margin-top: -25px;
  height: 46px;
  box-shadow: #000 0px 0px 5px;
  border-radius: 4px;
  padding: 4px;
}

.map-btn label {
  display: block;
  color: #000000;
  font-weight: normal;
  font-size: 6px;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

.sub-menu .map-btn {
  margin: 0px 2px;
}

.localPosition-popup {
  margin-left: -266px;
  margin-top: -50px;
  background-color: rgba(255, 255, 255, .5);
  width: 250px;
  height: 110px;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  line-height: 33px;
}

.localPosition-popup span[type=position] {
  background-color: #008680;
  color: #fff;
  border-radius: 5px;
  padding: 2px 10px;
  line-height: 20px;
  cursor: pointer;
  margin: 0 10px 0 10px;
}

.catalog-div {
  width: auto !important;
  height: auto !important;
  /* bottom: 160px;*/
  padding-bottom: 12px;
  margin-left: 34px;
  border-radius: 5px;
  max-width: 300px;
  /*min-width: 200px;*/
  position: absolute;
  overflow: auto;
  z-index: 100;
  top: 12px;
  background-color: #004a47ab;
}

.savebtn {
  /*background-color: #00afff;*/
  /*padding: 10px 20px;*/
  /*font-size: 14px;*/
  /*border-radius: 4px;*/
  margin-left: 50px !important;
}

.emptyinfo {
  font-size: 20px;
  margin: 50px 0px 50px 0;
  background-color: #c8ddfb;
  /*margin: 0px 0px 0px -80px;*/
}

.emptyinfo2 {
  font-size: 20px;
  margin: 0px 0px 10px 0;
  background-color: #c8fbcb;
  /*margin: 0px 0px 0px -80px;*/
}

.seeinfo {
  font-size: 20px;
  margin: 20px 0px 0px 0px;
  background-color: #d9ffe7;
}

.cbstform {
  margin: 0px 0px 0px -80px;
}
</style>
<style scoped lang="scss">
.create-isLoading {
  .el-loading-spinner {
    //top: 50%;
    //left: 50%;
    //margin-left: -55px;
    background: rgba(127, 126, 126, 0.7);
    //padding: 20px;
    //border-radius: 4px;
    //width: auto;
    //text-align: center;
    //position: absolute;

    i {
      color: #1c25de;
      font-size: 50px;
    }

    .el-loading-text {
      color: #1c25de;
      //color: #31e635;
      font-size: 30px;
    }
  }
}
</style>
